<?php
/**
 * User
 *
 * User is the main user class.
 * @author King Beto <apardo@adverit.com>
 * @version 1.0
 * @package AdMin Framework
 */

/**
 * User is the main user class.
 *
 * Here is an example
 * <code>
 * require_once(DIR_CLASSES ."/User.php");
 *
 * // Login example:
 *
 * $user = new User();
 * $user->setDBLink($dbLink);
 * $user->readSession();
 *
 *
 * if ($_REQUEST['action'] == "login") // with a post or a get
 * {
 *     $user->login($_POST['email'], $_POST['password']); // returns false if login fails
 * }
 *
 * if ($_REQUEST['action'] == 'logout')
 * {
 *     $user->logout();
 *     session_destroy();
 * }
 *
 * if ($user->isValidated)
 * {
 *     echo "Por favor, provea un usuario y clave correctos.";
 * }
 * else
 * {
 *     $userFields = $postulante->getFieldNames(); // this is a DataObjectWed inherited method :)
 *     foreach($userFields as $field)
 *     {
 *         echo $field .": ". $user->$field ."<br>";
 *     }
 *     echo "user email: ". $user->email;
 * }
 * </code>
 *
 * @package AdMin Framework
 */
class User extends DataObjectWedWithImages
{
    /**
     * Setted true if the user has been validated, otherwise is setted false.
     * @access private
     * @var boolean
     */
    public $isValidated = false;
    /**
     * When the user logins, the login date is updated.
     * @access public
     * @var boolean
     */
    public $upadteLastLogin = true;

    /**
     * When the users table has a login name and password that may be shared by other users,
     * this must be setted true.
     * @access private
     * @var boolean
     */
    protected $_usernameAndPasswordNotUnique = false;

    /**#@+
     * @access private
     * @var string
     */
    public $firstLogin  = false;
    protected $_dbTable    = "users";
    protected $_dbIndex    = "userID";
    protected $_dbUserName = "username";
    protected $_dbUserPass = "password";
    public $autoWriteSession = false;
    public $sessionKey  = "";
    public $sessionManager;
    /**#@-*/

    /**
     * The array containing the table fields of the DataObject.
     * @access private
     * @var array
     */
    public $_arFields = array('email',
                              'username',
                              'password',
                              'superuser',
                              'name',
                              'last_name',
                              'active',
                              'last_login');

    public function __construct()
    {
        parent::__construct();
        $this->sessionKey = $this->_dbTable;
        $this->sessionManager = new SessionManager();
    }

    public function readSession($forceDBGet=false)
    {
        if (!$this->_checkDBLink()) return 0;
		
		if ($this->_existsCookie())
		{
			list($sha1,$userID)= explode("-", $_COOKIE["cookieLoggedIn"]);

			if(!is_numeric($userID)) return 0;

			$sql = "SELECT ".$this->_dbIndex.", ".$this->_dbUserName.", ".$this->_dbUserPass." FROM ".$this->_dbTable." WHERE ".$this->_dbIndex."=".$userID;
			$this->_mysqlQuery($sql, $result);
			$row = mysql_fetch_assoc($result);
			if(sha1($row[$this->_dbUserName].$row[$this->_dbUserPass])!=$sha1)
			{
				$this->logout();
				return 0;
			}else{
				$this->login($row[$this->_dbUserName],$row[$this->_dbUserPass], true);
			}
		}elseif(!$this->sessionManager->exists($this->sessionKey)) {
			return 0;
		}

		$this->isValidated = true;
		$userAttrs = $this->sessionManager->get($this->sessionKey);
		if ($forceDBGet)
		{
			$this->get($userAttrs[$this->getID()]);
			if ($this->autoWriteSession) $this->writeSession();
		}
		else $this->set($userAttrs);

        return 1;
    }

    public function update($id=null)
    {
        $update = parent::update($id);
        if ($update)
        {
            if($this->sessionManager->exists($this->sessionKey) && $this->autoWriteSession) $this->writeSession();
            return $update;
        }
        return 0;
    }

    public function writeSession()
    {
        $userAttrs = array();
        foreach($this->_arFields AS $field)
        {
            $userAttrs[$field] = $this->$field;
        }
        $this->sessionManager->set($this->sessionKey, $userAttrs);
    }

	private function _existsCookie()
	{
		return !empty($_COOKIE["cookieLoggedIn"]);
	}

	private function _destroyCookie()
	{
		setcookie("cookieLoggedIn", '' , time() - 864000000, $this->_getDomainCookie(), $_SERVER['HTTP_HOST'] );
	}

	private function _createCookie()
	{

		$str = sha1($this->{$this->_dbUserName} . $this->{$this->_dbUserPass}) . "-" . $this->getID();
		setcookie("cookieLoggedIn", $str , time() + 864000000, $this->_getDomainCookie(), $_SERVER['HTTP_HOST'] );
	}

	/* This method is for only local.adverit.com */
	public function _getDomainCookie()
	{
	    // Online es siempre '/':
	    if(strpos($GLOBALS["CONF"]["url"]["root"], 'local.adverit.com') === FALSE) return '/';
	
		$urlRoot = str_replace("http://","",$GLOBALS["CONF"]["url"]["root"]);
		$domain = substr($urlRoot, strpos($urlRoot,"/"), strlen($urlRoot));
		return $domain;
	}

    public function login($inputName, $inputPassword, $keepLoggedIn=false)
    {
        $sql = "SELECT ". $this->_dbIndex .", ". $this->_dbUserPass ." FROM ". $GLOBALS["CONF"]["db"]["prefix"] . $this->_dbTable ." WHERE ". $this->_dbUserName ."='". $this->txt2sql($inputName) ."'";
        $this->_mysqlQuery($sql, $result);
        if((!$this->_usernameAndPasswordNotUnique && mysql_num_rows($result)==1) || ($this->_usernameAndPasswordNotUnique && mysql_num_rows($result)>=1))
        {
            list($userID, $userPassword) = mysql_fetch_row($result);
            mysql_free_result($result);

            if(strcmp($userPassword, $inputPassword) == 0)
            {
                $this->isValidated = true;
                $this->get($userID);

				if($keepLoggedIn)
					$this->_createCookie();
				else
					$this->_destroyCookie();

                if($this->upadteLastLogin)
                {
                    if($this->last_login == "0000-00-00 00:00:00" || $this->last_login == NULL)
                    {
                        $this->firstLogin = true;
                    }
                    $this->last_login = date("Y:m:d H:i:s");                    
                    mysql_query("UPDATE ". $GLOBALS["CONF"]["db"]["prefix"] . $this->_dbTable ." SET last_login='".$this->last_login."' WHERE ". $this->_dbIndex ."='". $userID ."'", $this->_dbLink);
                }
                $this->writeSession();
                return 1;
            }
            else return 0;
        }
        else return 0;
    }

    public function logout($commitSession=true)
    {
		$this->_destroyCookie();
        $this->isValidated = false;
        $this->sessionManager->delete($this->sessionKey);
        if($commitSession) $this->sessionManager->commit();
        return 1;
    }

    // keeped for backguard compatibility
    public function getField($field)
    {
        return $this->$field;
    }
}
?>
